<template>
  <div class="app-container">
    <div class="search-container">
      <el-form :model="searchParam" :inline="true">
        <el-form-item label="工厂">
          <el-select
            @keyup.enter="search"
            v-model="searchParam.plantId"
            placeholder="请选择工厂"
            clearable
            @change="selectPlant"
          >
            <el-option
              v-for="item in plantList"
              :key="item.id"
              :label="item.organizationCode"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="工作中心">
          <el-select
            @keyup.enter="search"
            v-model="searchParam.workCenterId"
            placeholder="请选择工作中心"
            clearable
          >
            <el-option
              v-for="item in workShopList"
              :key="item.id"
              :label="item.workshopName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="工作年份">
          <el-select
            @keyup.enter="search"
            v-model="searchParam.planYear"
            placeholder="请选择工作年份"
            clearable
            @change="selectYear"
          >
            <el-option
              v-for="item in yearOptions"
              :key="item"
              :value="item"
              :label="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="工作周">
          <el-select
            @keyup.enter="search"
            v-model="searchParam.planWeek"
            placeholder="请选择工作周"
            clearable
          >
            <el-option
              v-for="item in monthOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search"
            ><i-ep-search />搜索</el-button
          >
          <el-button @click="reset"><i-ep-refresh />重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never" class="table-container">
      <template #header>
        <el-button type="success" plain @click="openAddDialog(true, '')"
          ><i-ep-plus />新增</el-button
        >
        <el-button type="primary" @click="issueOrders()" plain
          ><i-ep-promotion />批量下达</el-button
        >
        <el-button @click="dailyBatchImport"
          ><template #icon><i-ep-upload /></template>导入</el-button
        >
        <el-button
          class="ml-3"
          @click="useDownload('/mdm/mdmmatgroup/export', '物料组', searchParam)"
        >
          <template #icon><i-ep-download /></template>导出</el-button
        >

        <!-- 导入周计划 -->
        <ImportExcel ref="weekImportRef" />
        <!-- 导入日计划 -->
        <ImportExcel ref="dailyImportRef" />
      </template>

      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="tableData"
        highlight-current-row
        max-height="600"
        @selection-change="handleSelectionChange"
        border
      >
        <el-table-column
          type="selection"
          width="55"
          align="center"
          :selectable="checkSelectable"
        />
        <el-table-column type="index" width="60" label="序号" align="center" />
        <el-table-column
          label="工厂"
          prop="plantCode"
          show-overflow-tooltip
          min-width="120"
          align="center"
        >
          <!-- <template #default="{ $index, row }">
            <span>{{
              getNameInfo(plantList, row.plantId, "organizationCode")
            }}</span>
          </template> -->
        </el-table-column>
        <el-table-column
          label="工作中心"
          prop="workCenterCode"
          show-overflow-tooltip
          min-width="100"
          align="center"
        >
          <!-- <template #default="{ $index, row }">
            <span>{{
              getNameInfo(workShopList, row.workCenterId, "workshopName")
            }}</span>
          </template> -->
        </el-table-column>
        <el-table-column
          label="工作年"
          prop="planYear"
          width="85"
          show-overflow-tooltip
          align="center"
        />
        <el-table-column
          label="工作周"
          prop="planWeek"
          width="85"
          show-overflow-tooltip
          align="center"
        />
        <el-table-column
          label="物料号/版本号"
          prop="materialCode"
          min-width="180"
          show-overflow-tooltip
        >
          <template #default="{ $index, row }">
            <span v-show="row.materialCode">{{ row.materialCode }}/</span>
            <span v-show="row.version">{{ row.version }}</span>
          </template>
        </el-table-column>
        <el-table-column label="卷料" width="60" align="center">
          <template #default="{ row }">
            <span>{{ filterRequestIds(row.requestPlanList) }}</span>
          </template>
        </el-table-column>
        <!-- <el-table-column
          label="班产"
          prop="yield"
          width="85"
          show-overflow-tooltip
          align="right"
        /> -->
        <el-table-column
          label="计划数量"
          prop="planQuantity"
          min-width="100"
          show-overflow-tooltip
          align="right"
        />
        <el-table-column
          label="生产批次"
          prop="planBatch"
          min-width="85"
          show-overflow-tooltip
          align="center"
        />
        <el-table-column
          label="状态"
          prop="planState"
          min-width="85"
          show-overflow-tooltip
          align="center"
        >
          <template #default="{ $index, row }">
            <el-tag
              v-if="row.planState !== null && row.planState !== undefined"
              :type="
                row.planState === 4
                  ? `success`
                  : row.planState === 1
                  ? `warning`
                  : row.planState === 0
                  ? 'info'
                  : ''
              "
              >{{ useDictionary("PlanStateList", row.planState) }}</el-tag
            >
          </template>
        </el-table-column>
        <el-table-column
          label="完成数量"
          prop="planFinishQuantity"
          width="85"
          show-overflow-tooltip
          align="right"
        />
        <el-table-column label="操作" width="250" align="center" fixed="right">
          <template #default="{ row, $index }">
            <el-button
              link
              type="primary"
              class="text-[13px]"
              @click="openAddDialog(true, '', row)"
              ><i-ep-edit />编辑</el-button
            >
            <el-button
              link
              type="primary"
              class="text-[13px]"
              @click="issueOrders(row)"
              :disabled="row.planState > 1"
              ><i-ep-position />下达</el-button
            >
            <el-button
              type="danger"
              link
              class="text-[13px]"
              @click="handleTableDelete(row)"
              ><i-ep-delete />删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-if="queryTotal > 0"
        v-model:total="queryTotal"
        v-model:page="current"
        v-model:limit="size"
        @pagination="search"
      />
    </el-card>
    <!-- 添加工作要求 -->
    <week-produce-order-edit
      :parentTaskId="addDialog.id"
      :visible="addDialog.visible"
      :title="addDialog.title"
      :data="addDialog.data"
      :plantList="plantList"
      :yearOptions="yearOptions"
      :monthOptions="monthOptions"
      @reset-table="search"
      @change-visible="changeVisible"
    />
  </div>
</template>

<script setup lang="ts" name="MESWEEKLYPRODUCEPLAN">
import { useDownload, useDictionary } from "@/utils/useTable";
import request from "@/utils/request";
import { getWorkShopsApi } from "@/api/plant/index";
import { getWeekNumber } from "@/utils/dateUtils";
import {
  SearchType,
  getMonthList,
  getYearList,
  getPlantList,
  getNameInfo,
  mockData,
  filterRequestIds,
} from "./index";

const currentYear = new Date().getFullYear(); // 当前年份
const currentWeek = getWeekNumber(new Date()); // 当前第几周

// 初始化搜索参数数据
const searchParamInit = {
  planWeek: currentWeek,
  planYear: currentYear,
  workCenterId: "",
  plantId: "",
};

let tableData: any = ref([]); // 表格数据

const checkSelectable = (row: any) => {
  if (row.planState == 0 || row.planState == 1) {
    return true;
  } else {
    return false;
  }
};

// 删除表格行
function handleTableDelete(row: any) {
  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    if (row.planFinishQuantity && Number(row.planFinishQuantity) > 0) {
      ElMessage.error("有已完成数量，不能删除");
    } else {
      await request({
        url: "/mes/mesproduceorder/delete",
        method: "post",
        data: { id: row.id },
      }).then(() => {
        ElMessage.success("删除成功");
        search();
      });
    }
  });
}

const searchParam = ref<SearchType>({ ...searchParamInit }); // 搜索框参数
const loading = ref(false); // 加载中
const queryTotal = ref(0); // 总计条数
const current = ref(1); // 当前页
const size = ref(10); // 当前页

// 最终请求参数
let queryParams = computed(() => {
  return {
    current: toRaw(current.value),
    size: toRaw(size.value),
    data: toRaw(searchParam.value),
    sort: {
      column: "code",
      orderBy: "asc",
    },
  };
});

const search = async () => {
  console.log("queryParams", queryParams.value);
  loading.value = true;
  tableData.value = [];
  const { data } = await request({
    url: "/mes/mesproduceplan/queryByPage",
    method: "post",
    data: toRaw(queryParams.value),
  }).finally(() => {
    loading.value = false;
  });
  queryTotal.value = data?.total || 0;
  tableData.value = data?.data || [];

  // 数据模拟
  tableData.value = mockData;
};

const reset = () => {
  // 搜索信息重置
  searchParam.value = { ...searchParamInit };
  current.value = 1;
  size.value = 10;
  tableData.value = [];
};

// 获取周列表
const monthOptions = ref<OptionType[]>();

// 获取年度列表
const yearOptions = ref();

// 年度变更重新获取月份
function selectYear(e: number) {
  if (e) {
    searchParam.value = { ...searchParam.value, planWeek: "" };
    monthOptions.value = getMonthList(e);
  } else {
    monthOptions.value = [];
    searchParam.value = { ...searchParam.value, planWeek: "" };
  }
}

// 工厂编号列表
const plantList: any = ref([]);

function selectPlant(e: string) {
  console.log("选择工厂", e);
  getWorkShopList(e);
}

// 工作中心列表
const workShopList: any = ref([]);
const getWorkShopList = async (id: string) => {
  const { data } = await getWorkShopsApi(id);
  if (id) {
    workShopList.value = data;
  } else {
    workShopList.value = [];
    searchParam.value = { ...searchParam.value, workCenterId: "" };
  }
};

onMounted(async () => {
  // 获取工厂列表
  plantList.value = await getPlantList();
  // 获取年列表
  yearOptions.value = await getYearList();
  // 获取周搜索列表
  monthOptions.value = getMonthList(currentYear);

  search();
});

// 导入
const dailyImportRef = ref();
async function dailyImportApiFunc(formdata: FormData, config: any) {
  await request.post("/mdm/mdmmatgroup/upload", formdata, config);
}
const dailyBatchImport = () => {
  let params = {
    title: "导入生产订单",
    tempApi: "/mdm/mdmmatgroup/exportTemp", //模板下载
    importApi: dailyImportApiFunc, // 导入
    getTableList: search, // 成功后回调
  };
  dailyImportRef.value.acceptParams(params);
};

// 多选
const selections = ref();
const ids = ref();
const handleSelectionChange = (selection: any) => {
  selections.value = selection;
  ids.value = selection.map((item: any) => item.id);
};

const dataTableRef = ref();

// 批量下达
const issueOrders = async (row?: any) => {
  if (!row && !ids.value?.length) {
    ElMessage.warning("请先进行勾选");
    return;
  }
  ElMessageBox.confirm("请确认是否下达?", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      const res: any = await request({
        url: "/mdm/mdmmatgroup/enabled",
        method: "post",
        data: {
          ids: ids,
        },
      });
      if (res.code == 200) {
        ElMessage({
          type: "success",
          message: "下达成功",
        });
        dataTableRef.value!.clearSelection();
        search();
      }
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消下达",
      });
      dataTableRef.value!.clearSelection();
    });
};

/** 打开工作要求表单弹窗 */
const addDialog = reactive<DialogOption>({
  id: "",
  visible: false,
  title: "",
  data: {},
});

// 获取生产订单信息
async function getProduceOrder(id: string) {
  const { data } = await request({
    url: `/mes/mesproduceorder/get/${id}`,
    method: "get",
  });
  // addDialog.data = data;

  //模拟数据
  addDialog.data = mockData[0];
}

// 打开弹窗
function openAddDialog(canEdit: boolean, id: "", roleObj?: any) {
  addDialog.id = id;
  roleObj?.id && getProduceOrder(roleObj?.id);
  addDialog.title = !canEdit ? "查看" : id ? "编辑" : "新增";
  addDialog.visible = true;
}

// 关闭弹窗回调
function changeVisible(value: boolean) {
  addDialog.visible = value;
}
</script>
<style lang="scss" scoped></style>
